/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package workingsafe;

import org.openstreetmap.gui.jmapviewer.Coordinate;
import org.openstreetmap.gui.jmapviewer.JMapViewer;
import org.openstreetmap.gui.jmapviewer.MapMarkerDot;
import org.openstreetmap.gui.jmapviewer.MapPolygonImpl;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
/**
 *
 * @author Administrador
 */
public class VentanaDelimitarAera extends javax.swing.JFrame implements MouseListener {
    
    private static final long serialVersionUID = 1L;
    final JMapViewer map = new JMapViewer();
    private LinkedList<Coordinate> coordenadasAux;
    private LinkedList<Coordinate> coordenadas;
    JButton btnCrearPoligono = new JButton("Crear Zona");
    JButton btnBorrarPuntos = new JButton("Eliminar Puntos");
    JButton btnEliminarPunto = new JButton("Eliminar ultimo punto");
    
    private static Sistema sistema;
    /**
     * Creates new form VentanaDelimitarAera
     */
    public VentanaDelimitarAera(Sistema sist) throws IOException {
        super("Delimitar Area de Riesgo");
        initComponents();        
        this.sistema = sist;
        coordenadas = new LinkedList<Coordinate>();
        coordenadasAux = new LinkedList<Coordinate>();
        
        map.addMouseListener(this);
     
        setLayout(new BorderLayout());
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setExtendedState(JFrame.MAXIMIZED_BOTH);
        
        JPanel pOpciones = new JPanel();
        pOpciones.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        pOpciones.setBackground(new java.awt.Color(255,204,51));
        add(pOpciones, BorderLayout.NORTH);

 //------------------------------------------------------------------------------       
       add(map, BorderLayout.CENTER);
       map.setDisplayPositionByLatLon(-34.876918,-56.218872, 11);
 //------------------------------------------------------------------------------
        
       
       btnCrearPoligono.setIcon(new ImageIcon(ImageIO.read( new File("iconos\\crear_poligono2.png"))));
       
        btnCrearPoligono.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (coordenadasAux.size() > 2){
                    for (Coordinate coor:coordenadasAux){
                        coordenadas.add(coor);
                        String lat = Double.toString(coor.getLat());
                        String lon = Double.toString(coor.getLon());
                        sistema.agregarCoordenadaAreaRiesgo(lat+","+lon);
                    }
                    System.out.println("cantidad de elementos en coordenadas " + coordenadas.size());
                    map.addMapPolygon( new MapPolygonImpl(coordenadas));
                    JOptionPane.showMessageDialog(null, "Se ha guardado el area de riesgo","Informacion",JOptionPane.INFORMATION_MESSAGE);
                    btnCrearPoligono.setEnabled(false);
                }
                else{
                    JOptionPane.showMessageDialog(null,"Debe seleccionar al menos 3 puntos para genera el área.", " Información", JOptionPane.INFORMATION_MESSAGE);
                }
            }
        });
        
        btnBorrarPuntos.setIcon(new ImageIcon(ImageIO.read( new File("iconos\\eliminar_poligono.png"))));
        
        btnBorrarPuntos.setIcon(new ImageIcon(ImageIO.read( new File("iconos\\eliminar_poligono.png"))));
        
        btnBorrarPuntos.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                map.removeAllMapMarkers();
                coordenadas.clear();
                coordenadasAux.clear();
                sistema.vaciarCoordenadasAreaRiesgo();
              btnCrearPoligono.setEnabled(true);
            }
        });
        
        btnEliminarPunto.setIcon(new ImageIcon(ImageIO.read( new File("iconos\\eliminar_nodo1.png"))));
        
        btnEliminarPunto.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (!coordenadas.isEmpty()){
                    map.removeAllMapMarkers();
                    coordenadas.removeLast();
                    coordenadasAux.removeLast();
                    sistema.borrarUltimaCoordenadaAreaRiesgo();
                    recorreCoordenadas();
                }
                else
                    JOptionPane.showMessageDialog(null,"No hay puntos ingresados.", " Información", JOptionPane.INFORMATION_MESSAGE);
            }
        });
        
        pOpciones.add(btnCrearPoligono);
        pOpciones.add(btnEliminarPunto);
        pOpciones.add(btnBorrarPuntos);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VentanaDelimitarAera.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VentanaDelimitarAera.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VentanaDelimitarAera.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VentanaDelimitarAera.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new VentanaDelimitarAera(sistema).setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(VentanaDelimitarAera.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    
    @Override
    public void mouseClicked(MouseEvent e) {
        
        //System.out.println(" --" + e.getPoint());
        Coordinate coord = map.getPosition(e.getPoint());
        if (e.getClickCount() == 1)
            map.addMapMarker(new MapMarkerDot(coord.getLat(),coord.getLon()));
        
        coordenadasAux.add(coord);
        if (!btnCrearPoligono.isEnabled())//si esta deshabilitado sigo dibujando el poligono
            coordenadas.add(coord);
    }

    private void recorreCoordenadas(){
        
        for (Coordinate coor: coordenadas){
            map.addMapMarker(new MapMarkerDot(coor.getLat(),coor.getLon()));
        }
    }
    @Override
    public void mouseEntered(MouseEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    public void mouseExited(MouseEvent e) {
        
        // TODO Auto-generated method stub
    }

    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
}
